package com.zjpavt.client.udp.artnet.service;

import com.zjpavt.client.hal.LoopManager;
import com.zjpavt.client.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class ArtNetLoopServiceImpl implements ArtNetService {
    /**
     * 变化最小周期
     */
    private static final long CHANGE_PERIOD = 100;
    /**
     * 上一条执行的指令 如果相同不执行
     */
    private String lastCommand;
    /**
     * 上一次修改的时间 如果太接近跳过
     */
    private AtomicLong lastChangeTime = new AtomicLong(0);
    /**
     * 对应回路设备的长度
     */
    private int loopNum = 12;
    public  ArtNetLoopServiceImpl() {
    }
    public ArtNetLoopServiceImpl(int loopNum) {
        this.loopNum = loopNum;
    }

    @Override
    public void execute(byte[] commandBytes) {
        int[] commandInts = new int[commandBytes.length];
        for (int beginIndex = 0; beginIndex < commandBytes.length; beginIndex++) {
            if (commandBytes[beginIndex] < 0) {
                commandInts[beginIndex] = 1;
            } else {
                commandInts[beginIndex] = 0;
            }
        }
        String sCommand = StringUtil.commandInt2String(commandInts);
        log.info(sCommand);
        if (sCommand != null && !sCommand.equals(lastCommand)) {
//          上次变化时间不大于100ms
            if (System.currentTimeMillis() - 100 < lastChangeTime.get()) {
                return;
            }
            lastChangeTime.set(System.currentTimeMillis());
            lastCommand = sCommand;
            LoopManager.getInstance().changeAutoLoopStatus(commandInts);
        }
    }
}
